package com.jgp.sys.repository;

import com.jgp.common.utils.ReflectUtil;
import org.hibernate.transform.AliasToBeanResultTransformer;

import javax.persistence.Column;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019-09-03
 */
public class ToBeanResultTransformer extends AliasToBeanResultTransformer {
    
    private Map<String,String> projectionName = new HashMap<>();
    private Map<String, Class> projectionType = new HashMap<>();
    
    public ToBeanResultTransformer(Class resultClass) {
        super(resultClass);
        List<Field> fields = ReflectUtil.getPersistFields(resultClass);
        for (Field field : fields) {
            Column column = field.getAnnotation(Column.class);
            projectionName.put(column.name(),field.getName());
            projectionType.put(column.name(),field.getType());
        }
    }
    
    @Override
    public Object transformTuple(Object[] tuple, String[] aliases) {
        String[] transAliases = new String[aliases.length];
        Object[] transValues = new Object[aliases.length];
        for (int i = 0; i < aliases.length; i++) {
            transAliases[i] = projectionName.get(aliases[i]);
            transValues[i] = ReflectUtil.cast(tuple[i], projectionType.get(aliases[i]));
            
        }
        return super.transformTuple(transValues, transAliases);
    }
}
